import Cookies from "js-cookie";
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { LoginDto } from "@/api/interface";
import API from "@/api";
export type MenuItemType = {
  id: number;
  name: string;
  path: string;
  parentId: number;
  children: MenuItemType[];
};

type UserBasicType = {
  userId: string;
  userName: string;
};

export type UserStateType = {
  userInfo: {
    menus: MenuItemType[];
    basicInfo: UserBasicType;
    token: string;
  };
};

const INIT_SATTE: UserStateType = {
  userInfo: {
    menus: [],
    basicInfo: {
      userId: "",
      userName: "",
    },
    token: "",
  },
};
export const login = createAsyncThunk(
  "user/login",
  /**
   * data: paylod，调用是传递来的
   * dispatch： 用于dispatch 其他action函数
   * getState： 获取当前store中的state
   * extra： 可以传递一些额外的参数，如axios实例，或者一些其他的数据
   */
  async (data: LoginDto & { loading?: boolean }, { dispatch }) => {
    const res = await API.user.login(data);
    if (res && res.access_token) {
      console.log("login success");

      dispatch(getInfo());
      dispatch(getMenus());
      return res.access_token;
    }
  },
);
export const getInfo = createAsyncThunk("user/getInfo", async () => {
  console.log("getInfo");

  return await API.user.getInfo();
});
export const getMenus = createAsyncThunk("user/getMenus", async () => {
  console.log("getMenus");

  return await API.menu.getMenus();
});

export const userSlice = createSlice({
  name: "user",
  initialState: INIT_SATTE,
  reducers: {},
  extraReducers: (builder) => {
    // login 的处理逻辑
    builder.addCase(login.fulfilled, (state, action) => {
      state.userInfo.token = action.payload;
      Cookies.set("token", action.payload);
    });
    builder.addCase(getInfo.fulfilled, (state, action) => {
      state.userInfo.basicInfo = action.payload;
    });
    builder.addCase(getMenus.fulfilled, (state, action) => {
      state.userInfo.menus = action.payload;
    });
  },
});
// export const { getInfo } = userSlice.actions;
export default userSlice.reducer;
